<template>
  <div>
    <Row>
      <Col span="8">
        <Card>
          <p slot="title">组织架构</p>
          <ButtonGroup>
            <Button type="primary" v-if="departManager_btn_add" @click="append">初始化</Button>
          </ButtonGroup>
          <Input placeholder="输入关键字进行过滤" v-model="filterText"></Input>
          <Tree :data="mainTreeData" ref="mainTree" :render="childRender"></Tree>
        </Card>
      </Col>
      <Col span="16">
        <Card>
          <p slot="title">组织相关</p>
          <Tabs value="first">
            <TabPane label="用户管理" name="first">
              <Row>
                <Input placeholder="用户名" v-model="listTableQuery.name" @on-enter="handlerTableRowFilter" style="width: 350px"></Input>
                <Button type="primary" @click="handlerTableRowFilter">搜索</Button>
                <Button type="primary" v-if="departManager_btn_user_add" @click="handleTableRowCreate">添加用户</Button>
              </Row>
              <Row>
                <Tables ref="table" searchable search-place="top" :columns="columns" v-model="childTableData">
                  <template slot="action" slot-scope="scope">
                    <Button v-if="departManager_btn_user_del" type="warning" size="small" @click="handleTableRowDelete(scope.row)">删除</Button>
                  </template>
                </Tables>
              </Row>

            </TabPane>
            <TabPane label="岗位管理" disabled name="second">标签二的内容</TabPane>
          </Tabs>
        </Card>
      </Col>
    </Row>
    <Modal v-if="departManager_btn_add" title="添加用户" v-model="dialogUserVisible" :mask-closable='false'>
      <depart-user @closeUserDialog="closeUserDialog" ref="departUser"></depart-user>
      <div slot="footer"></div>
    </Modal>
  </div>
</template>
<script>
import {
  getTree,
  addDepartObj,
  getDepartObj,
  delDepartObj,
  putDepartObj,
  addUserObj,
  delUserObj,
  getUsers
} from '@/api/admin/depart/index'
import { mapGetters } from 'vuex'
import { getTypeValue } from '@/api/dict/dictValue/index'
import DepartUser from './components/departUser'
import DepartPosition from './components/departPosition'
import { convertTree } from '@/libs/util'
import Tables from '_c/tables'
export default {
  components: {
    'depart-user': DepartUser,
    'depart-position': DepartPosition,
    Tables
  },
  watch: {
    filterText (val) {
      this.$refs.mainTree.filter(val)
    }
  },
  methods: {
    childRender (h, { root, node, data }) {
      return h('span', {
        style: {
          display: 'inline-block',
          width: '100%'
        },
        on: {
          click: () => {
            this.getTreeNodeData(data)
            // this.set(node,'selected',true)
          }
        },
        class: {
          // 'ivu-tree-title-selected': node.selected === true,
          'ivu-tree-title': true
        }
      },
      [
        h('span', [
          h('Icon', {
            props: {
              type: 'ios-folder-outline'
            },
            style: {
              marginRight: '8px'
            }
          }),
          h('span', data.title)
        ]),
        h('span', {
          style: {
            display: 'inline-block',
            float: 'right',
            marginRight: '32px'
          }
        }, [
          this.departManager_btn_edit ? h('Button', {
            props: Object.assign({}, this.buttonProps, {
              icon: 'ios-create',
              type: 'primary'
            }),
            style: {
              marginRight: '8px'
            },
            on: {
              click: () => { this.edit(node, data) }
            }
          }) : h('span'),
          this.departManager_btn_add ? h('Button', {
            props: Object.assign({}, this.buttonProps, {
              icon: 'ios-add',
              type: 'primary'
            }),
            style: {
              marginRight: '8px'
            },
            on: {
              click: () => { this.append(node, data) }
            }
          }) : h('span'),
          this.departManager_btn_del ? h('Button', {
            props: Object.assign({}, this.buttonProps, {
              icon: 'ios-trash',
              type: 'primary'
            }),
            on: {
              click: () => { this.remove(node, data) }
            }
          }) : h('span')
        ])
      ])
    },
    filterNode (value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    handleTableRowCreate () {
      if (this.currentTreeNodeId === undefined) {
        this.$Notice.warning({
          title: '提示',
          desc: '请先选择部门节点！'
        })
      } else {
        this.dialogUserVisible = true
      }
    },
    handleTableRowDelete (row) {
      this.$Modal.confirm({
        title: '提示',
        content: '此操作将永久删除用户, 是否继续?',
        onOk: () => {
          delUserObj({ departId: this.currentTreeNodeId, userId: row.id }).then(() => {
            this.$Notice.success({
              title: '成功',
              desc: '删除成功'
            })
            const index = this.childTableData.indexOf(row)
            this.childTableData.splice(index, 1)
          })
        }
      })
    },
    handlerTableRowFilter () {
      this.listTableQuery.departId = this.currentTreeNodeId
      const query = {
        departId: this.currentTreeNodeId,
        name: this.listTableQuery.name
      }
      getUsers(query).then(response => {
        this.childTableData = response.data.rows
      })
    },
    handlerMainTreeForm (formName) {
      const set = this.$refs
      set[formName].validate(valid => {
        if (valid) {
          putDepartObj(this.mainTreeForm.id, this.mainTreeForm).then(() => {
            this.editTreeFormFlag = false
            this.initmainTreeData()
            this.$Notice.success({
              title: '成功',
              desc: '修改成功'
            })
          })
        } else {
          return false
        }
      })
    },
    append (node, data) {
      let entity = {}
      if (data === undefined) {
        data = {}
        data.code = new Date().getTime()
        data.id = '-1'
        addDepartObj({ name: '根节点需修改', code: data.code, parentId: data.id }).then(() => {
          this.initmainTreeData()
        })
      } else {
        addDepartObj({ name: '子节点', code: new Date().getTime() + '_tmp', parentId: data.id }).then(response => {
          entity = response.data
          const newChild = { id: entity.id, title: entity.name, children: [], expand: true }
          if (!data.children) {
            this.$set(data, 'children', [])
          }
          data.children.push(newChild)
        })
      }
      // this.$refs.mainTree.setCurrentKey(data.id)
    },
    remove (node, data) {
      if (data.children.length > 0) {
        this.$Notice.warning({
          title: '失败',
          desc: '删除失败，该部门有其他子部门！'
        })
        return
      }
      const query = {
        departId: this.currentTreeNodeId
      }
      getUsers(query).then(response => {
        this.childTableData = response.data.rows
        if (this.childTableData.length > 0) {
          this.$Notice.warning({
            title: '失败',
            desc: '删除失败，部门存在用户！'
          })
          return
        }
        delDepartObj(data.id).then(() => {
          this.$Notice.success({
            title: '成功',
            desc: '删除成功'
          })
          this.initmainTreeData()
        })
        // this.$refs.mainTree.setCurrentKey(data.id)
      })
    },
    edit (node, data) {
      this.editTreeFormFlag = true
      getDepartObj(data.id).then(response => {
        this.mainTreeForm = response.data
      })
      this.$refs.mainTree.setCurrentKey(data.id)
    },
    resetMainTreeForm () {
      this.mainTreeForm = {
        code: '',
        name: ''
      }
    },
    initmainTreeData () {
      getTree().then(data => {
        const map = {
          value: 'id',
          label: 'label',
          children: 'children',
          childExpand: true
        }
        this.mainTreeData = convertTree(data, map)
      })
    },
    getTreeNodeData (data) {
      this.currentTreeNodeId = data.id
      this.currentTreeNode = data
      const query = {
        departId: this.currentTreeNodeId
      }
      getUsers(query).then(response => {
        this.childTableData = response.data.rows
      })
      // this.$refs.positionManager.getList(data.id)
    },
    closeUserDialog (selects) {
      this.dialogUserVisible = false
      const uIds = []
      let flag = false
      for (let i = 0; i < selects.length; i++) {
        flag = true
        for (let j = 0; j < this.childTableData.length; j++) {
          if (this.childTableData[j].id === selects[i].id) {
            flag = false
          }
        }
        if (flag) {
          this.childTableData.push(selects[i])
          uIds.push(selects[i].id)
        }
      }
      this.$refs.departUser.clear()
      addUserObj({ departId: this.currentTreeNodeId, userIds: uIds.join() }).then(() => {
        this.$Notice.success({
          title: '成功',
          desc: '保存成功'
        })
      })
    }
  },
  created () {
    this.initmainTreeData()
    // 加载树
    this.departManager_btn_edit = this.elements['departManager:btn_edit']
    this.departManager_btn_del = this.elements['departManager:btn_del']
    this.departManager_btn_add = this.elements['departManager:btn_add']
    this.departManager_btn_user_add = this.elements['departManager:btn_user_add']
    this.departManager_btn_user_del = this.elements['departManager:btn_user_del']
    getTypeValue('org_depart').then(response => {
      this.departTypeOptions = response.data.rows
    })
  },
  computed: {
    ...mapGetters(['elements'])
  },
  data () {
    return {
      columns: [
        { title: '姓名', key: 'name' },
        { title: '账户', key: 'username' },
        { title: '性别', key: 'sex' },
        { title: '描述', key: 'description' },
        { title: '操作',
          key: 'action',
          align: 'center',
          render: (h, params) => {
            return h(
              'div',
              this.$refs.table.$scopedSlots.action(params)
            )
          }
        }
      ],
      buttonProps: {
        type: 'default',
        size: 'small'
      },
      dialogUserVisible: false,
      departTypeOptions: [],
      departManager_btn_edit: false,
      departManager_btn_del: false,
      departManager_btn_add: false,
      departManager_btn_user_add: false,
      departManager_btn_user_del: false,
      filterText: '',
      editTreeFormFlag: false,
      currentTreeNodeId: undefined,
      currentTreeNode: {},
      mainTreeForm: {
        code: '',
        name: ''
      },
      listTableQuery: {
        name: undefined,
        departId: undefined
      },
      mainTreeFormRules: {
        code: [
          {
            required: true,
            message: '请输入编码',
            trigger: 'blur'
          },
          {
            min: 1,
            max: 20,
            message: '长度在 1 到 20 个字符',
            trigger: 'blur'
          }
        ],
        name: [
          {
            required: true,
            message: '请输入目录名',
            trigger: 'blur'
          },
          {
            min: 1,
            max: 20,
            message: '长度在 1 到 20 个字符',
            trigger: 'blur'
          }
        ]
      },
      mainTreeData: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      childTableData: []
    }
  }
}
</script>
